<template>
  <div>
    <!-- 导航栏区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <div class="seacrhBox">
        <!-- 搜索框 -->
        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
        <!--添加用户按钮-->
        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      </div>
      <!--  用户列表区域-->
      <el-table :data="userList" border style="width: 100%" :stripe="true">
        <el-table-column label="#" width="30" type="index"></el-table-column>
        <el-table-column prop="username" label="用户"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#41b883"
              @change="updateState(scope.row.id,scope.row.mg_state)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="getUserInfo(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="delUserInfo(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" @click="showCurrentRole(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" center @close="resetForm">
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="100px"
        class="addForm"
      >
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="addUserForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式:" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框区域 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" center @close="resetForm">
      <el-form
        :model="editUserForm"
        :rules="editUserRules"
        ref="editUserRef"
        label-width="100px"
        class="editForm"
      >
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式:" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editUserForm.id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配用户角色对话框区域-->
    <el-dialog title="分配角色" :visible.sync="allotRoleDialogVisible" width="50%">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <span>分配新角色：</span>
        <el-select v-model="checkedRole" placeholder="请选择">
          <el-option v-for="item in allRole" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotUserRole(userInfo.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义校验规则
    var checkMobile = (rule, value, cbfn) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!regMobile.test(value)) {
        cbfn(new Error('请输入正确的手机格式'))
      } else {
        cbfn()
      }
    }
    var checkEmail = (rule, value, cbfn) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!regEmail.test(value)) {
        cbfn(new Error('请输入正确的邮箱格式'))
      } else {
        cbfn()
      }
    }
    return {
      userList: [],
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      allotRoleDialogVisible: false,
      // 所有的角色信息
      allRole: [],
      // 选中的角色
      checkedRole: '',
      // 存放用户信息
      userInfo: {},
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserForm: {},
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const res = await this.$http.get('users', {
        params: this.queryInfo
      })
      // 如果查询成功提示用户
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.total = res.data.total
      this.userList = res.data.users
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 更新用户状态
    async updateState(uid, type) {
      const res = await this.$http.put(`users/${uid}/state/${type}`)
      if (res.meta.status !== 200) this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 重置表单
    resetForm() {
      // 清空添加用户对话框中的字段值和校验结果
      // this.$refs.addUserRef.resetFields()
      // 清空编辑用户对话框中的字段值和校验结果
      this.$refs.editUserRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addUserRef.validate(async vaild => {
        // 如果验证不通过，直接返回表单
        if (!vaild) return
        // 验证通过向服务器发送请求
        const res = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 隐藏对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 获取指定用户信息
    async getUserInfo(id) {
      // 显示编辑用户面板
      this.editDialogVisible = true
      // 获取用户信息
      const res = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) this.$message.error('获取用户信息失败')
      this.$message.success('获取用户信息成功')
      // 将获取的用户信息赋值给对话框
      this.editUserForm = res.data
    },
    // 提交更新后的用户信息
    editUser(id) {
      this.$refs.editUserRef.validate(async valid => {
        // 如果表单验证失败，直接返回表当
        if (!valid) return
        // 如果表单验证成功，向服务器发送请求
        const res = await this.$http.put(`users/${id}`, this.editUserForm)
        if (res.meta.status !== 200) this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新页面
        this.getUserList()
      })
    },
    // 删除用用户信息
    async delUserInfo(id) {
      const res = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) this.$message.error('删除用户失败!')
      this.$message.success('删除用户成功')
      // 刷新用户列表
      this.getUserList()
    },
    // 展示当前用户角色
    showCurrentRole(userInfo) {
      this.userInfo = userInfo
      // 获取所有角色
      this.getRoleList()
      // 打开对话框
      this.allotRoleDialogVisible = true
    },
    // 获取角色列表
    async getRoleList() {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      // 获取角色列表成功
      this.allRole = res.data
    },
    // 分配用户角色
    async allotUserRole(id) {
      if (this.checkedRole === '') {
        return this.$message.error('请选择角色')
      }
      // 已选中角色，更新用户的角色
      const res = await this.$http.put(`users/${id}/role`, {
        rid: this.checkedRole
      })
      // 注意，admin账户不允许修改用户角色
      if (res.meta.status !== 200) {
        return this.$message.error('分配用户角色失败')
      }
      // 分配用户角色成功
      this.$message.success('分配用户角色成功')
      // 刷新用户列表
      this.getUserList()
      // 重置选择框
      this.checkedRole = ''
      // 关闭对话框
      this.allotRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scope>
.seacrhBox {
  .el-input {
    width: 400px;
  }
  .el-button {
    margin-left: 30px;
  }
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}
.addForm,
.editForm {
  margin-top: 0;
}
</style>